<template>
  <el-dialog
    v-model="dialogVisible"
    title="服务管理"
    width="50%"
    :style="{ 'min-height': '550px' }"
  >
    <el-form :model="queryParams" label-width="80px" :inline="true">
      <el-form-item label="服务编号">
        <el-input
          v-model="queryParams.serviceId"
          placeholder="请输入服务编号"
          :style="{ width: '200px' }"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="query">查询</el-button>
        <el-button @click="createService" type="primary">新增服务</el-button>
      </el-form-item>
    </el-form>
    <!-- 新增服务弹窗 -->
    <el-dialog v-model="createDialog" title="创建服务" width="30%">
      <el-form :model="serviceForm" label-width="120px" ref="serviceFormRef" :rules="formRules">
        <el-form-item label="租户名">
          <el-input v-model="tenantInfo.name" :disabled="true" :style="{ width: '200px' }" />
        </el-form-item>
        <el-form-item label="选择服务" prop="serviceId">
          <el-select
            v-model="serviceForm.serviceId"
            filterable
            remote
            :reserve-keyword="false"
            placeholder="请选择服务"
            :remote-method="remoteList"
            :loading="loading"
          >
            <el-option
              v-for="item in serviceOptions"
              :key="item.id"
              :label="item.serviceName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="serviceForm.startTime"
            type="datetime"
            placeholder="请输入开始时间"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker v-model="serviceForm.endTime" type="datetime" :disabled="formType == 0" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(serviceFormRef)">提交</el-button>
          <el-button type="danger" @click="resetForm(serviceFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 新增服务弹窗 -->

    <!-- 服务列表 -->
    <el-table
      :data="tableData"
      style="width: 100%"
      v-loading="tableLoading"
      :cell-style="{ 'text-align': 'center' }"
      :header-cell-style="{ 'text-align': 'center' }"
    >
      <!-- <el-table-column prop="tenantId" label="租户编号" width="180" /> -->
      <el-table-column prop="serviceId" label="服务编号" width="180" />
      <el-table-column
        prop="startTime"
        :formatter="tableFormatterDate"
        label="服务开始时间"
        width="180"
      />
      <el-table-column
        prop="endTime"
        :formatter="tableFormatterDate"
        label="服务结束时间"
        width="180"
      />
      <el-table-column
        prop="createTime"
        :formatter="tableFormatterDate"
        label="创建时间"
        width="180"
      />
      <el-table-column fixed="right" label="操作" width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button link type="danger" size="small" @click="handleDel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-wrapper">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="pagination.total"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 服务列表 -->
  </el-dialog>
</template>

<script lang="ts" setup>
import { watch, onUnmounted } from 'vue'
import * as TenantServiceApi from '@/api/system/tenantService'
import * as ServiceApi from '@/api/system/service'
import { ElMessage, FormInstance, ElMessageBox } from 'element-plus'
const tenantInfo = ref<{
  name?: string
  id?: number
}>({}) // 租户信息
const queryParams = ref<{
  serviceId?: number
}>({}) // 查询参数
const dialogVisible = ref<boolean>(false) // 弹窗
const createDialog = ref<boolean>(false) // 创建服务弹窗
const serviceFormRef = ref<FormInstance>() // 表单ref
const serviceForm = ref<{
  id?: number
  name?: string
  serviceId?: number
  startTime?: Date | number
  endTime?: Date | number
}>({})
const formRules = reactive({
  serviceId: [{ required: true, message: '服务选择不能为空', trigger: 'blur' }],
  startTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }]
})
const formType = ref<number>(0) // 0 创建 1编辑
const loading = ref<boolean>(false) // 选择框loading
const serviceOptions = ref<ServiceApi.ServiceVO[]>([]) // 选择框列表项
const tableData = ref<TenantServiceApi.TenantServiceVO[]>([]) // 表格数据
const tableLoading = ref<boolean>(false) // 表格loading
const pagination = ref<{
  // 分页
  pageNo: number
  pageSize: number
  total: number
}>({
  pageNo: 1,
  pageSize: 10,
  total: 10
})
/** 表单选择框 远程搜索下拉显示 */
const remoteList = async (query: string) => {
  try {
    loading.value = true
    const { list } = await ServiceApi.getServicePage({
      pageNo: 1,
      pageSize: 100,
      serviceName: query
    })
    serviceOptions.value = list
    loading.value = false
  } catch (err) {
    serviceOptions.value = []
    ElMessage.error('获取服务列表失败')
  }
}

/** 获取租户名下的服务列表 */
const getTenantServicePage = async (params: {
  pageNo: number
  pageSize: number
  tenantId?: number
  serviceId?: number
}) => {
  tableLoading.value = true
  let res = await TenantServiceApi.getTenantServicePage(params)
  tableData.value = res.list
  pagination.value.total = res.total
  tableLoading.value = false
}

/** 监听startTime的改变，根据服务有效天数动态设置endTime，endTime不可编辑 */
const stopWatchStartTime = watch(
  serviceForm,
  () => {
    if (serviceForm.value.serviceId) {
      if (!serviceForm.value.startTime) {
        serviceForm.value.startTime = new Date()
      }
      const serviceItem = serviceOptions.value.find(
        (item) => item.id == serviceForm.value.serviceId
      )
      // 结束时间为服务有效期后的时间
      if (serviceItem) {
        let date = new Date(serviceForm.value.startTime as Date)
        let endTime = date.setDate(
          (serviceForm.value.startTime as Date).getDate() + serviceItem.validDays
        )
        serviceForm.value.endTime = endTime
      }
    } else {
      // 没有选择服务，结束时间为开始时间
      serviceForm.value.endTime = serviceForm.value.startTime
    }
  },
  { deep: true }
)

/** 组件注销，停止侦听器 */
onUnmounted(stopWatchStartTime)

/** 把日期转换成毫秒数 */
const DateToTimestamp = (date: Date | number) => {
  if (typeof date == 'number') {
    return date
  } else {
    return date.getTime()
  }
}

/** 提交表单 */
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    try {
      if (valid) {
        let startTime = DateToTimestamp(serviceForm.value.startTime as Date)
        let endTime = DateToTimestamp(serviceForm.value.endTime as Date)
        if (formType.value == 0) {
          await TenantServiceApi.createTenantService({
            tenantId: tenantInfo.value.id as number,
            serviceId: serviceForm.value.serviceId as number,
            startTime,
            endTime
          })
        } else if (formType.value == 1) {
          await TenantServiceApi.updateTenantService({
            id: serviceForm.value.id as number,
            tenantId: tenantInfo.value.id as number,
            serviceId: serviceForm.value.serviceId as number,
            startTime,
            endTime
          })
        }
        createDialog.value = false // 隐藏表单
        serviceFormRef.value?.resetFields() // 重置表单
        // 重新拉取最新的已开通服务列表
        const params = {
          pageNo: pagination.value.pageNo,
          pageSize: pagination.value.pageSize,
          tenantId: tenantInfo.value.id as number
        }
        getTenantServicePage(params)
        ElMessage.success('提交成功')
      } else {
        ElMessage.error('请完整填写信息')
      }
    } catch (err) {
      ElMessage.error('网络异常,请重新尝试')
    }
  })
}

/** 重置表单 */
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

/** 打开弹窗 */
const openDialog = async (data: object) => {
  try {
    tableLoading.value = true
    dialogVisible.value = true
    tenantInfo.value = data // 初始化租户信息
    queryParams.value = {} // 初始化查询参数
    serviceForm.value = {} // 初始化表单数据
    // 获取当前租户名下开通的服务列表
    const params = {
      pageNo: pagination.value.pageNo,
      pageSize: pagination.value.pageSize,
      tenantId: tenantInfo.value.id as number
    }
    await getTenantServicePage(params)
  } catch (err) {
    ElMessage.error('获取服务列表失败')
  }
}
defineExpose({ openDialog })

/** 创建服务 点击新增服务按钮 */
const createService = () => {
  formType.value = 0
  serviceForm.value = {}
  serviceFormRef.value?.resetFields() // 重置表单验证
  createDialog.value = true
}

/** 表格数据格式化 日期毫秒数 => 具体时间 */
const tableFormatterDate = (row: object, column: object, cellValue: number, index: number) => {
  return new Date(cellValue).toLocaleString()
}

/** 分页 */
const handleCurrentChange = (val: number) => {
  pagination.value.pageNo = val
  const params = {
    pageNo: pagination.value.pageNo,
    pageSize: pagination.value.pageSize,
    tenantId: tenantInfo.value.id as number
  }
  getTenantServicePage(params)
}

/** 编辑表单数据 */
const handleEdit = async (row: TenantServiceApi.TenantServiceVO) => {
  formType.value = 1
  // 获取当前租户名下开通的服务
  const { startTime, endTime } = row
  serviceForm.value.id = row.id
  serviceForm.value.serviceId = row.serviceId
  serviceForm.value.name = tenantInfo.value.name
  serviceForm.value.startTime = new Date(startTime)
  serviceForm.value.endTime = new Date(endTime)
  createDialog.value = true
  let serviceInfo = await ServiceApi.getService(row.serviceId)
  serviceOptions.value = [serviceInfo]
}

/** 删除表单数据 */
const handleDel = (row: TenantServiceApi.TenantServiceVO) => {
  ElMessageBox.confirm('您确定要删除这项服务吗?', 'Warning', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let del_status = await TenantServiceApi.deleteTenantService(row.id as number)
      if (del_status) {
        // 获取当前租户名下开通的服务列表
        const params = {
          pageNo: pagination.value.pageNo,
          pageSize: pagination.value.pageSize,
          tenantId: tenantInfo.value.id as number
        }
        await getTenantServicePage(params)
        ElMessage({
          type: 'success',
          message: '删除成功'
        })
      }
    })
    .catch()
}

/** 查询 */
const query = () => {
  if (!queryParams.value.serviceId) {
    ElMessage.error('请输入服务编号')
    return
  }
  pagination.value.pageNo = 1
  const params = {
    pageNo: pagination.value.pageNo,
    pageSize: pagination.value.pageSize,
    serviceId: queryParams.value.serviceId
  }
  getTenantServicePage(params)
}
</script>

<style lang="scss" scoped>
.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  align-items: flex-end;
  margin: 20px 0;
}
</style>
